<template>
	<view class="padding">
		<view class="cu-form-group">
			<view class="title">账号</view>
			<input placeholder="请输入账号" class="text-left" v-model="form.username"></input>
		</view>
		<view class="cu-form-group">
			<view class="title">密码</view>
			<input placeholder="请输入密码" type="password" class="text-left" v-model="form.password"></input>
		</view>
		<view class="cu-form-group">
			<view class="title">验证码</view>
			<input placeholder="请输入密码" class="text-left" v-model="form.code"></input>
			<img v-if="code.src" :src="code.src" style="width: 100px;height: 40px;" @click="refreshCode" />
		</view>
		<view class="padding" style="border-top: 1rpx solid #eee;">
			<button class="cu-btn shadow-blur block margin-tb-sm bottom-btn bg-blue" @tap="login">登录</button>
		</view>

	</view>
</template>

<script>
	import {
		loginByUserName
	} from '@/api/login.js'
	import {
		randomLenNum
	} from '@/utils/index.js'
	import config from 'config/env';
	import {
		encrypt
	} from '@/utils/aes.js'
	export default {
		data() {
			return {
				form: {
					username: 'hxmall',
					password: '123456',
					code: '',
					randomStr: '',
				},
				versionNumber: '1.0.0',
				code: {}
			}
		},
		created(){
			console.log("created")
			this.refreshCode();
		},
		methods: {
			login() {
				if (!this.form.username) {
					uni.showToast({
						title: '请输入账号',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				if (!this.form.password) {
					uni.showToast({
						title: '请输入密码',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				if (!this.form.password) {
					uni.showToast({
						title: '请输入密码',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				if (!this.form.code) {
					uni.showToast({
						title: '请输入验证码',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				console.log(config.encodeKey)
				let reqForm = {
					username: this.form.username,
					password: encrypt(this.form.password, config.encodeKey),
					code: this.form.code,
					randomStr: this.form.randomStr,
				}
				loginByUserName(reqForm).then(res => {
					let tokenInfo = res.data
					uni.setStorageSync('access_token', tokenInfo.tokenValue);
					uni.setStorageSync('expires_in', tokenInfo.tokenTimeout);
					uni.reLaunch({
						url: '/pages/home/index'
					})
				})

			},
			refreshCode() {
				this.form.randomStr = randomLenNum(4, true)
				this.code.src = config.basePath + '/code?randomStr=' + this.form.randomStr
			}
		}
	}
</script>

<style>
</style>
